package cn.ix.spring.security.service.impl;

import cn.ix.spring.security.entity.Account;
import com.google.common.collect.Lists;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lzw
 * @description CustomUserDetailsServiceImpl
 * @date 2022/3/2
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    private static Map<String, Account> userMap = new HashMap<>();

    static {
        userMap.put("admin", new Account("admin", "123456"));
        userMap.put("test", new Account("test", "123456"));
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Account account = userMap.get(userName);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        // 设置权限
        grantedAuthorities.add(new SimpleGrantedAuthority("account_edit"));
        // 设置角色 ROLE_
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_admin"));
        return new User(account.getUsername(), account.getPassword(), grantedAuthorities);
    }
}
